﻿var gulp = require('gulp'),
    minifycss = require('gulp-minify-css'),
    imagemin = require('gulp-imagemin'),
    clean = require('gulp-clean'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    replace = require('gulp-replace'),
    uglify = require('gulp-uglify'),
    gulpUsemin = require('gulp-usemin'),
    path = require('path'),
    rev = require('gulp-rev'),
    es = require('event-stream'),
    browserSync = require('browser-sync'),
    mergeStream = require('merge-stream'),
    minifyHTML = require('gulp-minify-html'),
    gulpUtil =require('gulp-util'),
    gulpLess = require('gulp-less'),
    gutil = require('gutil'),
    autoprefixer = require('gulp-autoprefixer');
//pc
var pcSrcPath = "./src/";
var pcDistPath = "./dist/";
var tmpPcPath = "./src/.tmp/";

var domain = "http://www.51ficc.com/static";

var minHtml = function (srcPath, distPath) {
    return gulp.src([srcPath + '/**/*.html'])
        //.pipe(replace(/images\//g, domain + '/images/'))
        .pipe(minifyHTML({conditionals: true, spare: true,quotes:true}))
        .pipe(gulp.dest(distPath))
}

//clean
var cleanDist = function (distPath) {
    return gulp.src([
        distPath + '/css/*.css',
        distPath + '/img/*',
        distPath + '/tpl/*',
        distPath + '/js/controllers/*',
        distPath + '/js/**/*'], {read: false})
        .pipe(clean())
        .pipe(notify({message: distPath + ' clean task complete'}));
};
// 图片
var imageMin = function (srcPath, distPath) {
    return gulp.src(srcPath)
        .pipe(imagemin({optimizationLevel: 5, progressive: true, interlaced: true}))
        .pipe(gulp.dest(distPath))
        //.pipe(imageIsuxMin(srcPath,distPath))
        .pipe(notify({message: 'Images task complete'}));
};
function usemin(src, dest, ifRev) {
    //src = /\.html$/.test(src) ? src : src + "/*.html";
    console.log(src);
    return gulp.src(src)
        .pipe(gulpUsemin({
            css: ifRev ? [minifycss({compatibility: 'ie8'}), rev()] : [minifycss({compatibility: 'ie8'})],
            jsVendor: ifRev ? [uglify(), rev()] : [uglify()],
            jsApp: ifRev ? [uglify(), rev()] : [uglify()]
        }))
        .pipe(gulp.dest(dest));
}
//js concat
var uglifyJs = function (srcPath, distPath) {
    console.log(srcPath);
    return gulp.src([srcPath])
        .pipe(uglify())
        .pipe(gulp.dest(distPath))
        .pipe(notify({message: distPath + ' concat Js ByPath task complete'}));
};
var copyFile = function (srcPath, distPath) {
    return gulp.src(srcPath)
        .pipe(gulp.dest(distPath));
}
var less= function(src, dest){
    console.log(dest);
    return gulp.src(src)
        // .pipe(changed(dest, {extension: '.css'}))
        .pipe(gulpLess())
        .on('error', gutil.log)
        .pipe(autoprefixer({
            browsers: [ /*'> 1%',*/ 'last 4 versions', 'Firefox > 20', 'Opera 12.1', 'ie 8', 'chrome >20']
        }))
        .pipe(gulp.dest(dest))
        .pipe(notify({ message: 'less task complete' }));

}
function onchange(e) {
    gulpUtil.log(gulpUtil.colors.cyan(path.basename(e.path)), 'was', e.type, gulpUtil.colors.green('running task..'));
    /* not good: could have loaded files before they are processed,
     and subject to partial construct thingy too. (less, browserify: change of imported files) */
    // server.changed(e.path);
}
//===================pc============================//
gulp.task('pc-clean', function () {
    return mergeStream(
        cleanDist(pcDistPath),
        cleanDist(tmpPcPath)
    );
});

gulp.task('pc-userMin', ['pc-clean','pc-less'], function () {
    return mergeStream(
        imageMin(pcSrcPath + "/img/*", tmpPcPath + "/img/"),
        usemin(pcSrcPath + "index.html", tmpPcPath, true),
        uglifyJs(pcSrcPath + "js/controllers/*.js", tmpPcPath + "js/controllers/"),
        //copyFile(pcSrcPath + "tpl/**",tmpPcPath+"tpl"),
        minHtml(pcSrcPath + "tpl", tmpPcPath + "tpl")
    );
});
gulp.task('pc-dist', ['pc-userMin'], function () {
    return mergeStream(
        // 仅copy
        gulp.src(tmpPcPath + "/**")
            .pipe(gulp.dest(pcDistPath))
    );
});
gulp.task('pc-less', function(){
    var lessArray = [pcSrcPath + "/less/app.less"];
    return less(lessArray, pcSrcPath + "css")
});
gulp.task('pc-watch',['browser'], function() {
    // 这个watch并没有刷新功能 e.g.有新文件进入，无法加入watcher
    // TODO: fix this
    gulp.watch(pcSrcPath + "/less/*.less", ['pc-less'])
        .on('change', onchange);
});
//=========================================================//
gulp.task('browser', function () {
    var path = "./src/";
    var files = [
        path + 'tpl/**/*.html',
        path + 'less/*.less',
        path + 'js/**/*.js'
    ];
    browserSync.init(files, {
        server: {
            baseDir: './'
        },
        port: 8080,
        browser: ["google chrome"],
        open: "external",
        startPath: path + "index.html"
    });
});

